package com.xing.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xing.cmnclient.DictFeignClient;
import com.xing.hosp.repository.HospitalRepository;
import com.xing.hosp.service.HospitalService;
import com.xing.hospital.model.hosp.Hospital;
import com.xing.hospital.model.vo.hosp.HospitalQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: xingfuhao
 * @Date: 2022/05/27/17:11
 */

@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {

    //private static final LOGGER log= LoggerFactory.getLogger(HospitalServiceImpl.class)

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;


    /**
     * 保存医院信息到mongoDB中去
     *
     * @param parameterMap
     */
    @Override
    public void save(Map<String, Object> parameterMap) {

        log.info("上传医院信息：{}" + JSONObject.toJSONString(parameterMap));
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(parameterMap), Hospital.class);

        //判断是否存在
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
        if (null != targetHospital) {
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            //0：未上线 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }


    }

    @Override
    public Hospital getByHascode(String hascode) {
        Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hascode);
        return hospitalByHoscode;
    }

    /**
     * 医院列表 多条件分页查询
     *
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //构建排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //构建分页规则
        //0 为第一页
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);
        //浅拷贝
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                //改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                //改变默认大小写忽略方式：忽略大小写
                .withIgnoreCase(true);

        //创建实例，构建规则
        Example<Hospital> example = Example.of(hospital, matcher);

        //调用方法实现查询
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        //获取查询list集合，遍历进行医院等级封装
        pages.getContent().stream().forEach(item -> {
            this.setHospitalHospType(item);
        });

        log.info("远程调用得到的数据,pages:{}", pages);

        return pages;
    }

    /**
     * 更新医院的上线状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateHospStatus(String id, int status) {
        //根据医院id获取对应的数据
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        //设置状态值
        hospitalRepository.save(hospital);

    }

    /**
     * 医院详情信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getHospById(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.setHospitalHospType(hospitalRepository.findById(id).get());
        //医院基本信息（包含医院等级）
        result.put("hospital", hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    /**
     * 获取医院名称
     *
     * @param hoscode
     * @return
     */
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (null != hospital) {
            return hospital.getHosname();
        }
        return null;
    }

    /**
     * 医院列表分页
     *
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {

        //创建pageable对象
        PageRequest pageable = PageRequest.of(page - 1, limit);
        //创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //hospitalSetQueryVo转化Hospital对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        //创建对象
        Example<Hospital> example = Example.of(hospital, matcher);
        //调用方法实现查询
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        //获取查询list集合，遍历进行医院等级封装
        pages.getContent().stream().forEach(item -> {
            this.setHospitalHospType(item);
        });
        return pages;
    }

    /**
     * 根据医院名称查询
     *
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    /**
     * 根据医院编号获取医院医院预约挂号详情
     *
     * @param hoscode
     * @return
     */
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHospitalHospType(this.getByHascode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }


    //获取查询list集合，遍历进行医院等级封装
    private Hospital setHospitalHospType(Hospital hospital) {
        //根据dictCode和value获取医院等级名称
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        //查询 省 市 地区 
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

//      hospital.getParam().put("fullAddress", provinceString + "-" + cityString + "-" + districtString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString);
        hospital.getParam().put("hostypeString", hostypeString);

        log.info("远程调用得到的数据,hospital:{}", hospital);
        return hospital;

    }


}
